﻿using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
//using System.Web.UI.HtmlControls;
//using System.Web.UI.WebControls;
//using System.Web.UI.WebControls.WebParts;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Logging;

/// <summary>
/// Summary description for AppUtil 
/// This class does the actual barcode generation and xml/xslt mapping
/// </summary>
public class AppUtil
{
    #region BarCode Stuff
    /// <summary>
    /// 
    /// </summary>
    /// <param name="imageToConvert"></param>
    /// <param name="formatOfImage"></param>
    /// <returns></returns>
    public static byte[] ConvertImageToByteArray(System.Drawing.Image imageToConvert, ImageFormat formatOfImage)
    {
        byte[] baData;

        try
        {
            using (MemoryStream ms = new MemoryStream())
            {
                Bitmap bm = new Bitmap(imageToConvert);

                bm = AppUtil.BitmapTo1Bpp(bm);
                bm.Save(ms, formatOfImage);

                baData = ms.ToArray();
            }
        }
        catch (Exception se)
        {
            LogError(se.Message);
            throw se;
        }

        return baData;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="errMsg"></param>
    public static void LogError(string errMsg)
    {
        LogEntry _LE = new LogEntry();
        _LE.Message = errMsg;
        _LE.TimeStamp = DateTime.Now;
        _LE.Categories.Add("Exceptions");
        _LE.Priority = 1;
        _LE.Severity = System.Diagnostics.TraceEventType.Error;

        Logger.Write(_LE);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="imageToConvert"></param>
    /// <param name="formatOfImage"></param>
    /// <returns></returns>
    public static string ConvertImageToBase64String(System.Drawing.Image imageToConvert, ImageFormat formatOfImage)
    {
        return Convert.ToBase64String(ConvertImageToByteArray(imageToConvert, formatOfImage));
    }

    /// <summary>
    /// Get a barcode Image
    /// </summary>
    /// <param name="barcodeData"></param>
    ///<returns></returns>
    public static System.Drawing.Image GetBarcodeImage(string barcodeData)
    {
        //Create a Barcode Professional object
        Neodynamic.WinControls.BarcodeProfessional.BarcodeProfessional bcp = new Neodynamic.WinControls.BarcodeProfessional.BarcodeProfessional();
        
        //Set the barcode symbology to Code 128
        bcp.Symbology = Neodynamic.WinControls.BarcodeProfessional.Symbology.Pdf417;  
  
        //Set the value to encode
        bcp.Code = barcodeData;
        bcp.Pdf417CompactionType = Neodynamic.WinControls.BarcodeProfessional.Pdf417CompactionType.Auto;
        bcp.Pdf417ErrorCorrectionLevel = Neodynamic.WinControls.BarcodeProfessional.Pdf417ErrorCorrection.Level6;
        //bcp.BarRatio = 3;
        //bcp.BarWidth = 1.25F;
        //bcp.BarHeight = .417F;
        //bcp.Pdf417Rows = 0;
        //bcp.Pdf417Columns = 0;
        //bcp.QuietZoneWidth = bcp.BarWidth * 2;
        //bcp.Pdf417AspectRatio = .5F;
        //bcp.TopMargin = .025F;
        //bcp.BottomMargin = .025F;

        float dpi = 145.0f;

        //Target size in inches
        SizeF targetArea = new SizeF( 4F, 1.5F );

        return bcp.GetBarcodeImage(dpi,targetArea);
    }

    /// <summary>
    /// Convert Bit Depth to 1
    /// </summary>
    /// <param name="img"></param>
    /// <returns></returns>
    public static Bitmap BitmapTo1Bpp(Bitmap img)
    {
        int w = img.Width;
        int h = img.Height;
        Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);
        BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);
        for (int y = 0; y < h; y++)
        {
            byte[] scan = new byte[(w + 7) / 8];
            for (int x = 0; x < w; x++)
            {
                Color c = img.GetPixel(x, y);
                if (c.GetBrightness() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8));
            }
            Marshal.Copy(scan, 0, (IntPtr)((int)data.Scan0 + data.Stride * y), scan.Length);
        }
        bmp.UnlockBits(data);

        return bmp;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="xmlDoc"></param>
    public static void EncriptXmlDoc(ref XmlDocument xmlDoc)
    {
        TripleDESCryptoServiceProvider tDESKey = new TripleDESCryptoServiceProvider();
        byte[] _Key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };
        tDESKey.Key = _Key;
        XmlElement FormElement = (XmlElement)xmlDoc.SelectSingleNode("/FORM");

        EncryptedXml exmlDoc = new EncryptedXml(xmlDoc);
        Byte[] encryptedForm = exmlDoc.EncryptData(FormElement, tDESKey, false);

        EncryptedData ed = new EncryptedData();
        ed.Type = EncryptedXml.XmlEncElementUrl;
        ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl);
        ed.CipherData = new CipherData();
        ed.CipherData.CipherValue = encryptedForm;

        EncryptedXml.ReplaceElement(FormElement, ed, false);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="_AppUtil"></param>
    /// <param name="_XmlDoc"></param>
    /// <param name="encriptedElement"></param>
    public static void DecriptXmlDoc(ref BarcodeProcessor _AppUtil, ref XmlDocument _XmlDoc, ref XmlElement encriptedElement)
    {
        //Decript        
        TripleDESCryptoServiceProvider tDESKey = new TripleDESCryptoServiceProvider();
        byte[] _Key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };
        tDESKey.Key = _Key;

        EncryptedData encryptedData = new EncryptedData();

        encryptedData.Type = EncryptedXml.XmlEncElementUrl;
        encryptedData.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl);

        encryptedData.LoadXml(encriptedElement);

        EncryptedXml exml = new EncryptedXml();

        Byte[] encryptedForm = exml.DecryptData(encryptedData, tDESKey);
        exml.ReplaceData(encriptedElement, encryptedForm);

        _AppUtil.XMLDoc = _XmlDoc;
        Guid _Guid = _AppUtil.GetFormID();
    }
    #endregion
}
